<?php

/**
 * This is the model class for table "inventory_batches".
 *
 * The followings are the available columns in table 'inventory_batches':
 * @property integer $id
 * @property integer $item_id
 * @property integer $location_id
 * @property string $model
 * @property integer $model_id
 * @property integer $quantity
 * @property string $unit_cost
 * @property integer $quantity_on_hand
 * @property string $date_created
 */
class InventoryBatch extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return InventoryBatch the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'inventory_batches';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('item_id, location_id, model, model_id, quantity, unit_cost, quantity_on_hand, date_created', 'required'),
			array('item_id, location_id, model_id, quantity, quantity_on_hand', 'numerical', 'integerOnly'=>true),
			array('model', 'length', 'max'=>25),
			array('unit_cost', 'length', 'max'=>10),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, item_id, location_id, model, model_id, quantity, unit_cost, date_created', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'location' => array(self::BELONGS_TO, 'InventoryLocation', 'location_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'item_id' => 'Item',
			'location_id' => 'Location',
			'model' => 'Model',
			'model_id' => 'Model',
			'quantity' => 'Quantity',
			'unit_cost' => 'Unit Cost',
			'date_created' => 'Date Created',
		);
	}
	
	public function adjustBatchQuantity($itemId, $amount, $method='fifo')
	{
		$order_by = ($method == 'fifo') ? 'asc' : 'desc';
		
		// check to see if a batch with current quantity on hand exists
		$active_batch_exists = self::model()->exists('item_id=:itemId and quantity_on_hand > 0', array(':itemId'=>$itemId));
		
		// if one or more does, use inventory method to select 
		// the approriate batch
		if ($active_batch_exists)
		{
			$batch = self::model()->find(array(
						'select'=>'*',
						'condition'=>'item_id=:itemId and quantity_on_hand > :quantityOnHand', 
						'params' => array(':itemId'=>$itemId, ':quantityOnHand'=>0),
						'order' => "date_created {$order_by}"));
			
			$batch->quantity_on_hand += $amount;
			$batch->save();
			
		}
		else 
		{
			$newBatch = new InventoryBatch;
			$newBatch->newManualEntry(array(
										'location_id'=>InventoryLocation::getDefaultLocation(),
										'quantity'=>$amount,
										'quantity_on_hand'=>$amount,
										'unit_cost'=>0
									  ));
									  
			$newBatch->item_id = $itemId;
			$newBatch->save(false);
			
			$batch = $newBatch;
		}
		
		
		
	}
	
	public function newManualEntry($data)
	{
		$this->model = 'Manual Entry';
		$this->model_id = 0;
		$this->location_id = $data['location_id'];
		$this->quantity = $data['quantity'];
		$this->quantity_on_hand = $data['quantity'];
		$this->unit_cost = $data['unit_cost'];
		$this->date_created = date("Y-m-d H:i:s");
	}
	
	public function batchRecordExists($itemId, $model)
	{
		$model_type = get_class($model);
		$exists = self::model()->exists("item_id=:itemId and model=:model and model_id=:modelId", 
									array(':itemId'=>$itemId, ':model'=>$model_type, ':modelId'=>$model->id));
		return $exists;
	}
	
	public function findItemBatchId($itemId, $model)
	{
		$model_type = get_class($model);
		
		$batch = self::model()->find("item_id=:itemId and model=:model and model_id=:modelId", 
										array(':itemId'=>$itemId, ':model'=>$model_type, ':modelId'=>$model->id));
		return $batch->id;
	}
	
	public function findItemBatch($itemId, $model)
	{
		$model_type = get_class($model);
		
		$batch = self::model()->find("item_id=:itemId and model=:model and model_id=:modelId", 
										array(':itemId'=>$itemId, ':model'=>$model_type, ':modelId'=>$model->id));
		return $batch;
	}
	

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('item_id',$this->item_id);
		$criteria->compare('location_id',$this->location_id);
		$criteria->compare('model',$this->model,true);
		$criteria->compare('model_id',$this->model_id);
		$criteria->compare('quantity',$this->quantity);
		$criteria->compare('unit_cost',$this->unit_cost,true);
		$criteria->compare('date_created',$this->date_created,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
}